package com.na.proxy;

import java.util.Arrays;

public class ByteArrayBuffer {

	private byte[] buffer;
	private int count;
	
	public ByteArrayBuffer() {
		this(8);
	}
	
	public ByteArrayBuffer(int size) {
		buffer = new byte[size];
		count = 0;
	}
	
	public synchronized void write(int b) {
		write((byte) b);
	}
	
	public synchronized void write(byte b) {
		ensureCapacity(count + 1);
		buffer[count] = b;
		count += 1;
	}
	
	public synchronized void write(byte[] b, int off, int len) {
		ensureCapacity(count + len);
		System.arraycopy(b, off, buffer, count, len);
		count += len;
	}
	
	private void ensureCapacity(int newCap) {
		int len = buffer.length;
		if (newCap > len) {
			int newLength = len << 1;
			if (newLength < newCap) {
				newLength = newCap;
			}
			buffer = Arrays.copyOf(buffer, newLength);
		}
	}
	
	public synchronized int size() {
		return count;
	}
	
	public byte[] getArray() {
		return buffer;
	}
	
	public synchronized byte[] toByteArray() {
		return Arrays.copyOf(buffer, count);
	}
	
}
